<?php

namespace App\Tables;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Article extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at', 'published_at'];

    protected $fillable = [
        'title', 'sub_title', 'content', 'openness',
        'status', 'published_at', 'category_id', 'tag_ids', 'has_image',
        'is_top', 'read_quantity'
    ];

    protected $appends = [
        'status_text',
        'tags_text',
        'category_text',
        'openness_text'
    ];

    protected $casts = [
        'tag_ids' => 'json',
        'is_top' => 'boolean',
        'has_image' => 'boolean'
    ];

    /**
     * 判断文章是否有图
     * @return bool
     */
    public function hasImage() {
        $pattren = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]))[\'|\"].*?[\/]?>/";

        return preg_match($pattren, $this->content) === false ? false : true;
    }

    /**
     * 获取公开级别文字
     * @return string
     */
    public function getOpennessTextAttribute()
    {
        switch ($this->openness) {
            case 'public':
                return '公开';
            case 'private':
                return '私密';
            case 'password':
                return '密码访问';
            default:
                return '';
        }
    }

    /**
     * 获取文章分类文字
     * @return string
     */
    public function getCategoryTextAttribute()
    {
        $parents = (new Categories)->getParents($this->category_id);

        $texts = array();
        foreach ($parents as $item) {
            $texts[] = $item->name;
        }

        return implode('/', $texts);
    }


    /**
     * 获取标签文字
     * @return mixed
     */
    public function getTagsTextAttribute()
    {
        if (empty($this->attributes['tag_ids'])) {
            return '';
        }

        $tags = Tag::whereIn('id', $this->tag_ids)->get(['name']);

        if ($tags->isEmpty()) {
            return '';
        }

        return $tags->implode('name', '、');
    }

    /**
     * 获取文章状态文字
     * @return string
     */
    public function getStatusTextAttribute()
    {
        switch ($this->status) {
            case 'draft':
                return '草稿';
            case 'wait_audit':
                return '待审核';
            case 'rejection':
                return '未通过';
            case 'published':
                return '已发布';
            default:
                return '';
        }
    }
}
